package com.hee.erp.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hee.erp.modules.entity.WfNode;
import com.hee.erp.modules.mapper.WfNodeMapper;
import com.hee.erp.modules.service.IWfNodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author weizehong
 * @since 2022-05-15
 */
@Service
public class WfNodeServiceImpl extends ServiceImpl<WfNodeMapper, WfNode> implements IWfNodeService {

    @Override
    public void removeByMainId(String mainId) {
        LambdaQueryWrapper<WfNode> queryWrapper = new LambdaQueryWrapper<>(new WfNode());

        queryWrapper.eq(WfNode::getWfMainId, mainId);

        this.remove(queryWrapper);

    }

    @Override
    public WfNode getNodeChainByMainId(String mainId) {
        List<WfNode> list = this.listByMainId(mainId);
        WfNode node = createNodeChain(list);
        return node;
    }

    private WfNode createNodeChain(List<WfNode> list) {
        //首先找出开始节点
        Optional<WfNode> nodeOptional = list.stream().filter(wfNode -> StringUtils.isBlank(wfNode.getParentId()) || wfNode.getParentId().equals("0")).findFirst();
        if(nodeOptional.isPresent()){
            WfNode firstNode = nodeOptional.get();
            WfNode nowNode = firstNode;
            WfNode nextNode = filterNodeByParentId(list,nowNode.getId());

            while (nextNode != null){
                nowNode.setNext(nextNode);
                nowNode = nextNode;

                nextNode = filterNodeByParentId(list,nowNode.getId());
            }
            return firstNode;
        }else{
            return null;
        }
    }

    private WfNode filterNodeByParentId(List<WfNode> list,String parentId){
        Optional<WfNode> nodeOptional = list.stream().filter(wfNode -> wfNode.getParentId() != null && wfNode.getParentId().equals(parentId)).findFirst();
        return nodeOptional.isPresent() ? nodeOptional.get() : null;
    }

    private List<WfNode> listByMainId(String mainId) {
        LambdaQueryWrapper<WfNode> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WfNode::getWfMainId, mainId);
        return this.list(queryWrapper);
    }
}
